<template>
	<view>
		<nav-bar>
			<template v-if="checkCount <= 0">
				<template slot="left">
					<view style="width: 60rpx;height: 60rpx;"
						class="flex align-center justify-center bg-light rounded-circle ml-3"
						hover-class="bg-hover-light" @tap="backUp" v-if="current">
						<text class="iconfont icon-fanhui"></text>
					</view>
					<text class="font-md ml-3">
						{{ current ? current.name : '首页' }}
					</text>
				</template>
				<template slot="right">
					<view style="width: 60rpx;height: 60rpx;"
						class="flex align-center justify-center bg-light rounded-circle mr-3"
						hover-class="bg-hover-light" @tap="openAddDialog">
						<text class="iconfont icon-zengjia"></text>
					</view>
					<view style="width: 60rpx;height: 60rpx;"
						class="flex align-center justify-center bg-light rounded-circle mr-3"
						hover-class="bg-hover-light" @click="openSortDialog">
						<text class="iconfont icon-gengduo"></text>
					</view>
				</template>
			</template>
			<template v-else>
				<view slot='left' class="font-md ml-3 text-primary" @click="handleCheckAll(false)">取消</view>
				<text class="font-md font-weight-bold">已选中{{checkCount}}个</text>
				<view slot='right' class="font-md mr-3 text-primary" @click="handleCheckAll(true)">全选</view>
			</template>
		</nav-bar>
		<!-- 搜索框 -->
		<view class="px-3 py-2">
			<view class="position-relative">
				<view style="height: 70rpx;width: 70rpx;position: absolute;top: 0;left: 0;"
					class="flex align-center justify-center text-light-muted">
					<text class="iconfont icon-sousuo"></text>
				</view>
				<input style="height: 70rpx;padding-left: 70rpx;" type="text" class="bg-light font-md rounded-circle"
					placeholder="搜索网盘文件" @input="search" />
			</view>
		</view>
		<fList v-for="(item,index) in list" :item="item" :key='index' :index='index' @select="select"
			@click="doEvent(item)">
		</fList>
		<!-- 底部操作条 -->
		<view v-if="checkCount > 0">
			<view style="height: 115rpx;"></view>
			<view style="height: 115rpx;" class="flex align-stretch bg-primary text-white fixed-bottom">
				<view class="flex-1 flex flex-column align-center justify-center" style="line-height: 1.5;"
					v-for="(item,index) in actions" :key="index" hover-class="bg-hover-primary"
					@click="handleBottomEvent(item)">
					<text class="iconfont" :class="item.icon"></text>
					{{item.name}}
				</view>
			</view>
		</view>
		<!-- 是否要删除 -->
		<f-dialog ref="delete">
			是否删除选中？
		</f-dialog>
		<!-- 重命名 -->
		<f-dialog ref="rename">
			<input type="text" v-model="renameValue" class="flex-1 bg-light rounded px-2" style="height: 95rpx;"
				placeholder="重命名" />
		</f-dialog>
		<!-- 新建文件夹 -->
		<f-dialog ref="newdir">
			<input type="text" v-model="newdirname" class="flex-1 bg-light rounded px-2" style="height: 95rpx;"
				placeholder="新建文件夹名称" />
		</f-dialog>
		<!-- 添加操作条 -->
		<uni-popup ref="add" type="bottom">
			<view class="bg-white flex" style="height: 200rpx;">
				<view class="flex-1 flex align-center justify-center flex-column" hover-class="bg-light"
					v-for="(item,index) in addList" :key="index" @tap="handleAddEvent(item)">
					<text style="width: 110rpx;height: 110rpx;"
						class="rounded-circle bg-light iconfont flex align-center justify-center"
						:class="item.icon + ' ' + item.color"></text>
					<text class="font text-muted">{{item.name}}</text>
				</view>
			</view>
		</uni-popup>

		<!-- 排序框 -->
		<uni-popup ref="sort" type="bottom">
			<view class="bg-white">
				<view v-for="(item,index) in sortOptions" :key="index"
					class="flex align-center justify-center py-3 font border-bottom border-light-secondary"
					:class="index === sortIndex ? 'text-main' : 'text-dark'" hover-class="bg-light"
					@click="changeSort(index)">
					{{item.name}}
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import navBar from '@/components/common/nav-bar.vue'
	import fList from "@/components/common/f-list.vue"
	import fDialog from '@/components/common/f-dialog.vue';
	import uniPopup from '@/components/uni-ui/uni-popup/uni-popup.vue'
	import {
		fileList,
		remove,
		rename,
		createdir,
		search,
		upload,
		share
	} from '../../api/user.js'

	export default {
		data() {
			return {
				dirs: [], // 保存当前文件夹记录
				renameValue: '',
				renameItem:{},//要修改名称的对象
				newdirname: '',
				sortIndex: 0,
				sortOptions: [{
					name: "按名称排序",
					key: "name"
				}, {
					name: "按时间排序",
					key: "created_time"
				}],

				list: [],
				addList: [{
					icon: "icon-file-b-6",
					color: "text-success",
					name: "上传图片"
				}, {
					icon: "icon-file-b-9",
					color: "text-primary",
					name: "上传视频"
				}, {
					icon: "icon-file-b-2",
					color: "text-warning",
					name: "新建文件夹",
				}, ]
			}
		},
		components: {
			navBar,
			fList,
			fDialog,
			uniPopup
		},
		onLoad() {
			// console.log('onload');
			this.getData()
		},
		methods: {
			// 获取数据
			async getData() {
				// console.log(123);
				let orderby = this.sortOptions[this.sortIndex].key
				let res = await fileList({
					dir_id: this.dir_id,
					orderby
				})
				this.list = this.formatList(res.rows)
			},
			// 进行数据处理
			formatList(list) {
				let arr = list.map(v => {
					let type = 'none'
					if (v.isdir == 1) {
						type = 'dir'
					} else {
						type = (v.ext.split('/')[0]) || 'none'
					}
					return {
						type,
						checked: false,
						...v
					}
				})
				return arr
			},
			// 返回上一个目录
			backUp() {
				this.dirs.pop()
				this.getData()
				uni.setStorage({
					key: 'dirs',
					data: JSON.stringify(this.dirs)
				})
			},
			// 打开添加操作条
			openAddDialog() {
				this.$refs.add.open()
			},
			openSortDialog() {
				this.$refs.sort.open()
			},
			// 点击列表
			doEvent(item) {
				// console.log(item);
				switch (item.type) {
					case 'image':
						let images = this.list.filter(item => {
							return item.type === 'image'
						})
						uni.previewImage({
							current: item.url,
							urls: images.map(item => item.url)
						})
						break;
					case 'video':
						uni.navigateTo({
							url: '../video/video?url=' + item.url + '&title=' + item.name,
						});
						break;
					default:
						this.dirs.push({
							id: item.id,
							name: item.name
						})
						this.getData()
						uni.setStorage({
							key: 'dirs',
							data: JSON.stringify(this.dirs)
						})
						break;
				}
			},
			// 切换顺序
			changeSort(index) {
				this.sortIndex = index
				this.getData()
				this.$refs.sort.close()
			},
			// 搜索
			async search(e) {
				if (e.detail.value == '') return this.getData()
				let res = await search({
					keyword: e.detail.value
				})
				this.list = this.formatList(res.rows)
			},
			// 选中列表
			select(e) {
				console.log('e:', e);
				this.list[e.index].checked = e.value
			},
			// 全选/取消全选
			handleCheckAll(checked) {
				this.list.forEach(item => {
					item.checked = checked
				})
			},
			handleAddEvent(item) {
				console.log('item.name', item.name);
				this.$refs.add.close()
				switch (item.name) {
					case '新建文件夹':
						this.$refs.newdir.open(async (close) => {
							if (this.newdirname == '') {
								return uni.showToast({
									title: '文件夹名称不能为空',
									icon: 'none'
								});
							}
							let res = await createdir({
								dir_id: this.dir_id,
								name: this.newdirname
							})
							this.getData()
							uni.showToast({
								title: '新建文件夹成功',
								icon: 'none'
							});
							close()
							this.newdirname = ''
						})
						break;
					case '上传图片':
						uni.chooseImage({
							count: 9,
							success: (res) => {
								res.tempFiles.forEach(v => {
									// console.log('v', v);
									this.handleUpload(v, 'image')
								})
							}
						})
						break;
					case '上传视频':
						uni.chooseVideo({
							count: 1,
							success: (res) => {
								let name = ''
								let size = 0
								// #ifndef H5
								name = res.tempFilePath.substring(res.tempFilePath.lastIndexOf('/') + 1)
								size = res.size
								// #endif
								this.handleUpload({
									path: res.tempFilePath,
									name,
									type: 'video',
									size
								})
							}
						})
						break;
					default:
						break
				}
			},
			handleBottomEvent(item) {
				switch (item.name) {
					case '删除':
						this.$refs.delete.open(async (close) => {
							uni.showLoading({
								title: '删除中···',
								mask: false
							})
							let ids = this.checkList.map(v => v.id).join(',')
							console.log('ids:', ids);
							try {
								let res = await remove({
									ids
								})
								this.getData()
								uni.showToast({
									title: '删除成功',
									icon: 'none'
								})
								uni.hideLoading()
							} catch (err) {
								uni.hideLoading()
							}
							close()
						})
						break;
					case '重命名':						
						this.renameValue = this.checkList[0].name
						let renameItem=this.checkList[0];						
												
						this.$refs.rename.open(async (close) => {
							if (this.renameValue == '') {
								return uni.showToast({
									title: '文件名称不能为空',
									icon: 'none'
								});
							}
							renameItem.name = this.renameValue
							// console.log('id:', that.checkList[0]);
							let res = await rename({
								id: renameItem.id,
								dir_id:this.dir_id,
								name: this.renameValue
							})
							uni.showToast({
								title: '重命名成功',
								icon: 'none'
							})
							close()
						})
					case '下载':
						this.download()
					case "分享":
						this.share()
						this.handleCheckAll(false)
						break;
					default:
						break;
				}
			},

			// 生成唯一ID
			genID(length) {
				return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
			},

			async handleUpload(file, type) {				
				const key = this.genID(8)				
				let name = file.name
				if (!name) {
					console.log(123456);
					name = file.path.substring(file.path.lastIndexOf('/') + 1)
				}
				let obj = {
					name,
					type: type,
					size: file.size,
					key,
					progress: 0,
					status: true,
					create_time: (new Date()).getTime()
				}
				// console.log('obj', obj);

				// 创建上传任务
				this.$store.dispatch('createUploadJob', obj)

				// 上传
				await upload({
					dir_id: this.dir_id,
					filePath: file.path,
				}, (p) => {
					this.$store.dispatch('updateUploadJob', {
						state: true,
						progress: p,
						key
					})
				})
				this.getData()
			},

			// 下载, 只下载非目录文件
			download() {
				this.checkList.forEach(item => {
					if (item.isdir == 0) {
						const key = this.genID(8)

						let obj = {
							name: item.name,
							type: item.type,
							size: item.size,
							key,
							progress: 0,
							status: true,
							create_time: (new Date()).getTime()
						}

						// 创建下载任务
						this.$store.dispatch('creatDownLoadJob', obj)

						let url = item.url

						let downTask = uni.downloadFile({
							url,
							success: (res) => {
								console.log('down, res', res);
								if (res.statusCode == 200) {
									// #ifdef H5
									uni.saveFile({
										tempFilePath: res.tempFilePath
									})
									// #endif
								}
							}
						})

						downTask.onProgressUpdate((res) => {
							this.$store.dispatch('updateDownLoadJob', {
								progress: res.progress,
								status: true,
								key
							})
						})
					}
				})

				uni.showToast({
					title: '已加入下载任务',
					icon: 'none'
				})

				this.handleCheckAll(false)
			},

			// 分享
			async share() {
				let res = await share({
					dir_id: this.checkList[0].id
				})

				uni.showModal({
					showCancel: false,
					content: res,
					success: (result) => {
						// #ifndef H5
						if (result.confirm) {
							uni.setClipboardData({
								data: result,
								success: () => {
									uni.showToast({
										title: '复制成功',
										icon: 'none'
									})
								}
							})
						}
						// #endif
					}
				})

			}


		},
		computed: {
			// dir_id 
			dir_id() {
				let l = this.dirs.length
				if (!l) {
					return 0
				}
				return this.dirs[l - 1].id
			},
			// 选中列表
			checkList() {
				return this.list.filter(item => item.checked)
			},
			// 选中数量
			checkCount() {
				return this.checkList.length
			},

			// current
			current() {
				let l = this.dirs.length
				if (!l) return false
				return this.dirs[l - 1]
			},
			// 操作菜单
			actions() {
				if (this.checkCount > 1) {
					return [{
						icon: "icon-xiazai",
						name: "下载"
					}, {
						icon: "icon-shanchu",
						name: "删除"
					}]
				}
				return [{
					icon: "icon-xiazai",
					name: "下载"
				},
				// {
				// 	icon: "icon-fenxiang-1",
				// 	name: "分享"
				// },
				{
					icon: "icon-shanchu",
					name: "删除"
				}, {
					icon: "icon-chongmingming",
					name: "重命名"
				}]
			},
		}
	}
</script>

<style>

</style>
